require('date-utils');
var async = require('async');
var AV = require('leanengine');
//var async = require('async');


//操作产品的模型信息
var User = AV.Object.extend("_User");
var Card = AV.Object.extend("Card");
var Level = AV.Object.extend("Level");
var Recharge=AV.Object.extend("RechargeRecord");
var AmountF=AV.Object.extend("AmountFlow");
var Order=AV.Object.extend("Order");
module.exports = {
    //获取用户等级
    getLevelByOpenID:function(openid){
        var query = new AV.Query(User)
        var promise = new AV.Promise();
        if(openid){
            query.equalTo('openid',openid);
            query.first().then(function(res){
                if(res){
                    promise.resolve(res.get('level_id'));
                }else{
                    promise.reject('not found user by openid');
                }
            }).catch(function(err){
               promise.reject('system error');
            });
            return promise;
        } else{
            return new AV.Promise.error("111 openid should not be empty!");
        }
    },
    //by jun 获取绑定的手机号码
    getbdPhone:function(openid){
        var query = new AV.Query(User);
        var promise = new AV.Promise();
        if(openid) {
            query.equalTo('openid', openid);
            query.first().then(function(res){
                if(res){
                    promise.resolve(res.get('bdPhone'));
                    //promise.resolve(res);
                }else{
                    promise.reject('not found user by openid');
                }
            }).catch(function(err){
                promise.reject('system error');
            });
            return promise;
        }else{
            return new AV.Promise.error("222 openid should not be empty!");
        }
    },
    //by jun 获取用户昵称
    getNicknameByOpenid:function(openid){
        var query = new AV.Query(User);
        var promise = new AV.Promise();
        if(openid) {
            query.equalTo('openid', openid);
            query.first().then(function(res){
                if(res){
                    promise.resolve(res.get('nickname'));
                }else{
                    promise.reject('not found user by openid');
                }
            }).catch(function(err){
                promise.reject('system error');
            });
            return promise;
        }else{
            return new AV.Promise.error("222 openid should not be empty!");
        }
    },
    //获取用户积分
    getPointsByOpenID:function(openid){
        var query = new AV.Query(User);
        var promise = new AV.Promise();
        if(openid) {
            query.equalTo('openid', openid);
            query.first().then(function(res){
                if(res){
                    promise.resolve(res.get('point'));
                }else{
                    promise.reject('not found user by openid');
                }
            }).catch(function(err){
                promise.reject('system error');
            });
            return promise;
        }else{
            return new AV.Promise.error("222 openid should not be empty!");
        }
    },
    //获取用户余额
    getAmountByOpenID:function(openid){
        var query = new AV.Query(User);
        var promise = new AV.Promise();
        if(openid){
            query.equalTo('openid',openid);
            query.first().then(function(res){
               if(res){
                    promise.resolve(res.get('amount'));
               } else{
                    promise.reject('not found user by openid');
               }
            });
            return promise;
            //return  query.first();
        }else{
            return new AV.Promise.error("333 openid should not be empty!");
        }
    },
    /**
     * 增加用户积分
     * @param userid  用户编号
     * @param point   增加积分
     * @returns code  0 正常、400:用户编号不能为空、402:增加积分不能为空、9999:系统异常
     * @auth James 2015-08-23
     */
    updatePoints:function(userid,point){

        if(!userid) {
            return new AV.Promise.error({code:400});     //用户编号不能为空
        }

        if(!point) {
            return new AV.Promise.error({code:402});     //增加积分不能为空
        }

        var promise = new AV.Promise();

        //创建用户的查询实例
        var query = new AV.Query(User);

        async.waterfall([
            function(callback){
                query.get(userid).then(function(res){
                    callback(null,res,res.get('point'));
                }).catch(function(err){
                    callback({code:9999,reason:err});
                });
            },
            function(res,jf,callback){
                res.set('point',parseInt(jf)+parseInt(point));
                res.save().then(function(post){
                    callback(null,{code:0,ysjf:parseInt(jf),dqjf:parseInt(jf)+parseInt(point)});
                }).catch(function(err){
                    callback(err);
                });
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });

        return promise;
    },

    //判断用户是否绑定手机
    ifBingPhone:function(uid){
        if(uid){
            var promise = new AV.Promise();
            var query = new AV.Query(User);
            query.get(uid).then(function(user){
                if(user){
                    var ifbdp=user.get('ifBindPhone');
                    var bdp=user.get('bdPhone');
                    promise.resolve({ifbdp:ifbdp,bdp:bdp});
                }else{
                    promise.reject('not found user by uid');
                }
            })
            return promise;
        } else {
            return new AV.Promise.error('uid should not be empty!');
        }

    },

    /*
    * 向指定手机发送验证码
    * */
    sendsmsphone:function(phone){
        var promise = new AV.Promise();
        AV.Cloud.requestSmsCode(phone).then(function(){
            //发送成功
            promise.resolve(true);
        }, function(err){
            //发送失败
            promise.reject('sned smscode failed');
        });
        return promise;
    },

    /*
    * 验证smscode
    * */
    yzsmscode:function(smscode,phone,openid){
        var promise = new AV.Promise();
        AV.Cloud.verifySmsCode(smscode, phone).then(function(){
            //验证成功
            var query = new AV.Query(User);
            query.equalTo('openid',openid);
            query.first().then(function(res){
                if(res){
                    res.set('bdPhone',phone);
                    res.set('ifBindPhone',true);
                    res.save().then(function(post){
                        promise.resolve(true);
                    }).catch(function(error){
                        console.log(error);
                    })
                }else{
                    promise.resolve(false);
                }
            });

        }, function(err){
            //验证失败
            promise.reject('verify smscode failed');
        });
        return promise;
    },
    /*
    * 用于验证更换手机发送的验证码
    * */
    yzghsmsmcode:function(scode,ophone){
      var promise = new AV.Promise();
        AV.Cloud.verifySmsCode(scode,ophone).then(function(){
            promise.resolve(true);
        },function(err){
            promise.reject('verify smscode failed');
        });
        return promise;
    },

    //绑定用户手机号
    bindPhone:function(openid,phone){
        var promise = new AV.Promise();
        var query = new AV.Query(User);
        if(openid && phone){
            query.equalTo('openid',openid);
            query.first().then(function(res){
                if(res){
                    res.set('bdPhone',phone);
                    res.set('ifBindPhone',true);
                    res.save().then(function(post){
                        promise.resolve(true);
                    }).catch(function(error){
                        console.log(error);
                    })
                }else{
                    promise.resolve(false);
                }
            });
            return promise;
        }else{
            return new AV.Promise.error('openid or phone should not be empty!');
        }
    },

    //保存用户支付密码
    saveyepwd:function(uid,pwd){
        var promise = new AV.Promise();
        var query = new AV.Query(User);
        if(uid && pwd){
            query.get(uid).then(function(getuser){
                getuser.set('yepassword',pwd);
                getuser.save().then(function(res){
                    promise.resolve(true);
                }).catch(function(error){
                    console.log(error);
                    promise.resolve(false);
                })
            });
            return promise;
        }else{
            return new AV.Promise.error('uid or pwd should not be empty!');
        }
    },

    //判断用户是否已经设置支付密码
    ifSetpwd:function(uid){

        var promise = new AV.Promise();
        var query = new AV.Query(User);
        if (uid) {

            query.get(uid).then(function (getuser) {
                promise.resolve(getuser.get('yepassword'))
            }).catch((function(error){
                console.log(error);
            }))
            return promise;
        } else {
            return new AV.Promise.error('uid should not be empty!');
        }
    },

    //修改支付密码
    reSetpwd:function(ypwd,xgpwd,uid){
        var promise = new AV.Promise();
        var query = new AV.Query(User);
        query.get(uid).then(function(getuser){
            if(ypwd == getuser.get('yepassword')){
                getuser.set('yepassword',xgpwd);
                getuser.save().then(function(res){
                    promise.resolve({pwdres:'pwd'})
                }).catch(function(error){
                    promise.resolve({pwdres:'cwpwd'})
                })
            }else{
                promise.resolve({pwdres:'ypwd'})
            }
        })
        return promise;
    },

    //向绑定手机用户发送修改密码验证码
    findcode:function(uid){
        var promise = new AV.Promise();
        var query = new AV.Query(User);
        async.waterfall([
            function(callback){
                query.get(uid).then(function(getuser){
                    if(getuser.get('ifBindPhone')){
                        var phone=getuser.get('bdPhone');
                        callback(null,phone);
                    }else{
                        //promise.resolve({bdphone:false,sendcode:false});
                        return callback({bdphone:false,sendcode:false});
                    }
                })
            },
            function(res,callback){
                AV.Cloud.requestSmsCode(res).then(function(){
                    //发送成功
                    callback(null,{bdphone:true,sendcode:true});
                }, function(err){
                    //发送失败
                    return callback({bdphone:true,sendcode:false});
                });
            }
        ],function(err,result){
            if(err){
                promise.resolve(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },

    //验证验证码，保存新支付密码
    savezhpwd:function(code,zhpwd,uid){
        var promise = new AV.Promise();
        var query = new AV.Query(User);
        async.waterfall([
            function(callback){
                query.get(uid).then(function(getuser){
                    var pho=getuser.get('bdPhone');
                    callback(null,pho);
                })
            },
            function(phone,callback){
                AV.Cloud.verifySmsCode(code,phone).then(function(){
                    //promise.resolve(true);
                    callback(null,{vcode:true})
                },function(err){
                    //promise.reject('verify smscode failed');
                    callback({vcode:false,setpwd:false})
                });
            },
            function(res,callback){
                if(res.vcode){
                    query.get(uid).then(function(guser){
                        guser.set('yepassword',zhpwd);
                        guser.save().then(function(res){
                            callback(null,{vcode:true,setpwd:true})
                        })
                    })
                }else{
                    callback({vcode:false,setpwd:false})
                }
            }
        ],function(error,result){
            if(error){
                promise.resolve(error)
            }else {
                promise.resolve(result)
            }
        });
        return promise;
    },


    //获取用户头像
    getUserHeadIMG:function(openid){
        var promise = new AV.Promise();
        var query = new AV.Query(User);
        if(openid){
            query.equalTo('openid',openid);
            query.first().then(function(res){
                if(res){
                    promise.resolve(res.get('headimgurl'));
                }else{
                    promise.reject('not found user by openid');
                }
            });
            return promise;
        }else{
            return new AV.Promise.error('555 openid should not be empty!');
        }
    },
    //获取用户加入时间
    getUserJoinTime:function(openid){
        var promise = new AV.Promise();
        var query = new AV.Query(User);
        if(openid){
            query.equalTo('openid',openid);
            query.first().then(function(res){
                if(res){
                    var time = res.createdAt;
                    var date = new Date(time).toFormat('YYYY-MM-DD');
                    promise.resolve(date.toString());
                }else{
                    promise.reject('not found user by openid')
                }
            })
            return promise;
        }else{
            return new AV.Promise.error('666 openid should not be empty!');
        }
    },
    //根据等级编号，获取等级信息
    getLevelInfo:function(objectId){
        var promise = new AV.Promise();
        var query = new AV.Query(Level);
        if(objectId){
            query.equalTo('objectId',objectId);
            query.first().then(function(res){
                if(res){
                    promise.resolve(res);
                }else{
                    promise.reject('not found user by openid')
                }
            })
            return promise;
        }else{
            return new AV.Promise.error('objectId should not be empty!');
        }
    },
    //验证充值卡是否合法
    checkCard:function(cardNo,cardPwd){
        var promise = new AV.Promise();
        var query = new AV.Query(Card);
        if(cardNo && cardPwd){
            query.equalTo('cardno',cardNo);
            query.equalTo('cardPwd',cardPwd);
            query.equalTo('used',0);
            query.first().then(function(res){
                if(res){
                    // 合法返回充值卡面额
                    promise.resolve(res.get('par'));
                }else{
                    // 不合法返回-1
                    promise.reject(-1);
                }
            });
            return promise;
        }else{
            return new AV.Promise.error("cardno or cardpwd should not be empty");
        }
    },
    //使用充值卡
    useCard:function(cardpar,openid){
        var promise = new AV.Promise();
        var query = new AV.Query(User);
        if(cardpar && openid){
            async.waterfall([
                function(callback){
                    query.equalTo('openid',openid);
                    query.first().then(function(res){
                        if(res){
                            var amount = res.get('amount');
                            callback(null,res,amount);
                        }else{
                            callback(null,false);
                        }
                    }).catch(function(err){
                        callback(err);
                    });
                },
                function(res,amount,callback){
                    var amount = amount+cardpar;
                    res.set('amount',amount);
                    res.save().then(function(post){
                        callback(null,true);
                    }).catch(function(err){
                        callback(err);
                    });
                }
            ],function(err,result){
                if(err){
                    promise.resolve(false);
                }else{
                    promise.resolve(true);
                }
            });
            return promise;
        }else{
            return new AV.Promise.error('cardpar or openid should not be empty');
        }
    },
    //更改充值卡状态为已使用
    updateCardStatus:function(cardno){
        var promise = new AV.Promise();
        var query = new AV.Query(Card);
        if(cardno){
            async.waterfall([
                function(callback){
                    query.equalTo('cardno',cardno);
                    query.first().then(function(res){
                        if(res){
                            callback(null,res);
                        }else{
                            callback(null,false);
                        }
                    }).catch(function(err){
                        callback(err);
                    });
                },
                function(res,callback){
                    res.set('used',1);
                    res.save().then(function(post){
                        callback(null,true);
                    }).catch(function(err){
                        callback(err);
                    });
                }
            ],function(err,result){
                if(err){
                    promise.resolve(false);
                }else{
                    promise.resolve(true);
                }
            });
            return promise;
        }else{
            return new AV.Promise.error('cardno should not be empty');
        }
    },

    /*
    * 使用微信充值余额,创建一个充值订单
    * type 1:等待微信支付回调   2:支付回调成功，已经更新用户余额成功
    * */
    chongZhi:function(orderid,uid,amount){

        if(!orderid){
            return new AV.Promise.error({code:502});        //订单编号不能为空
        }

        if(!uid){
            return new AV.Promise.error({code:505});        //用户编号不能为空
        }
        var promise = new AV.Promise();
        var recharge = new Recharge();
        var rech = {orderid:orderid,uid:uid,type:1,pay:parseInt(amount)};
        recharge.save(rech).then(function(res){

            if(res){
                // 保存充值记录成功

                promise.resolve({code:0,orderid:orderid,amount:amount});
            }else{
                // 不合法返回-1

                promise.reject({code:-1,msg:''});
            }
        }).catch(function(err){
            promise.reject({code:9999,reason:err});
        });
        return promise;

    },

    /*
     * 余额充值成功回调
     * */
    notify:function(orderid,je){

        console.log('NOTIFY METHOD CALLED:'+new Date());
        if(!orderid){
            return new AV.Promise.error({code:502});        //订单编号不能为空
        }

        if(!je){
            return new AV.Promise.error({code:505});        //支付金额不能为空
        }
        var promise = new AV.Promise();
        //var query = new AV.Query(Recharge);
        var uid='';
        var newAmount=0;
        var afteramount=0;
        var beforeamount=0;
        var content='';
        async.waterfall([
            function(callback){
                //根据orderid查到uid，type
                var query = new AV.Query(Recharge);
                query.equalTo('orderid',orderid);
                query.equalTo('type',1);//待充值的订单
                query.first().then(function(res){
                    //callback(null,res);
                    if(res == null){
                        return callback({code:401,msg:'该订单已处理'});
                    }
                    var pay=res.get('pay');

                    switch (parseInt(pay)){
                        case 100:
                            pay=106;
                            break;
                        case 300:
                            pay=318;
                            break;
                        case 500:
                            pay=538;
                            break;
                        case 1000:
                            pay=1068;
                            break;
                        default:
                            pay = 1;
                    }
                    uid=res.get('uid');
                    var queryuser = new AV.Query(User);
                    newAmount=pay;
                    queryuser.get(uid)
                        .then(function(userch){
                            beforeamount=userch.get('amount');
                            afteramount=beforeamount+pay;
                            userch.increment('amount',pay);
                            userch.save().then(function(resu){
                                callback(null,res);
                            }).catch(function(err){
                                callback(err);
                            });
                        })
                        .catch(function(error){
                            callback(error);
                        });
                }).catch(function(err){
                    callback({code:9999,reason:err});
                });
            },
            function(res,callback){
                //余额更新成功，将type置为2
                res.set('type',2);
                res.save().then(function(resre){
                    callback(null,resre);
                }).catch(function(error) {
                    callback(error);
                });
            },
            function(res,callback){
                //保存充值流水
                content='订单'+orderid+'使用余额充值，账户余额增加'+newAmount+'元.';
                var amountflow=new AmountF();
                var am={userid:uid,newamount:newAmount,afteramount:afteramount,beforeamount:beforeamount,content:content};
                amountflow.save(am).then(function(restt){
                    callback(null,res);
                }).catch(function(error){
                    callback(error);
                })
            }
        ],function(err,result){
            if(err){
                console.log(err);
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;

    },


    /**
     * 扣除余额
     * @param userid  用户编号
     * @param je      扣除金额
     * @returns code  0 正常、400:用户编号不能为空、401:扣除金额不能为空、9999:系统异常
     * @auth James 2015-08-23
     */
    minusAmount:function(userid,je){

        if(!userid) {
            return new AV.Promise.error({code:400});     //用户编号不能为空
        }

        if(!je) {
            return new AV.Promise.error({code:401});     //扣除金额不能为空
        }

        var promise = new AV.Promise();

        //创建用户的查询实例
        var query = new AV.Query(User);

        query.get(userid).then(function(res) {
            res.increment('amount', 0 - parseFloat(je / 100));
            res.save().then(function (post) {
                var dqye = parseFloat(post.get('amount'));
                var ysye = parseFloat(post.get('amount')) + parseFloat(je / 100);

                promise.resolve({code: 0,ysye:ysye,dqye:dqye});

            }).catch(function (err) {
                promise.reject(err);
            });
        });

        return promise;
    },
    /**
     * 增加余额
     * @param userid  用户编号
     * @param je      增加金额
     * @returns code  0 正常、400:用户编号不能为空、403:增加金额不能为空、9999:系统异常
     * @auth James 2015-09-11
     */
    plusAmount:function(userid,je){

        if(!userid) {
            return new AV.Promise.error({code:400});     //用户编号不能为空
        }

        if(!je) {
            return new AV.Promise.as({code:0,msg:'不增加金额'});     //增加金额不能为空
        }

        var promise = new AV.Promise();

        //创建用户的查询实例
        var query = new AV.Query(User);

        query.get(userid).then(function(res) {
            res.increment('amount', 0 + parseFloat(je));
            res.save().then(function (post) {
                promise.resolve({code: 0});
            }).catch(function (err) {
                promise.reject(err);
            });
        });

        return promise;
    },
    //获取用户余额
    getAmount:function(objectId){

        if(!objectId){
            return new AV.Promise.error({code:400});        //用户编号不能为空
        }

        var query = new AV.Query(User);
        var promise = new AV.Promise();

        async.waterfall([
            function(callback){
                //根据产品编号获取该对象
                query.get(objectId).then(function(res){
                    callback(null,res);
                }).catch(function(err){
                    callback({code:9999,reason:err});       //code:9999 系统错误
                });
            },
            function(res,callback){
                //获取用户余额
                var amount = res.get('amount');
                callback(null,{code:0,amount:amount});
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    /**
     * @author Scor 2015-9-29
     * @return object{code:int,msg:string}
     * @param uid
     */
    isNewBuyer:function(uid){
        if(uid){
            var query=new AV.Query(Order);
            var promise = new AV.Promise();
            query.equalTo("uid",uid);
            query.greaterThanOrEqualTo("status",2000);
            query.count().then(function (res) {
                if(res>0){
                    promise.reject({code:1223,msg:"你不是新用户"});
                }else{
                    promise.resolve({code:0,msg:"你是新用户"});
                }
            });
            return promise;
        }else{
            return new AV.Promise.error({code:1200,msg:"uid不能为空！"});
        }
    }
};


